package org.rcy.framework.rpc.registry;

import org.rcy.framework.rpc.RpcUtils;
import org.rcy.framework.rpc.service.AbstractRpcService;
import org.rcy.framework.rpc.base.RpcService;
import org.rcy.framework.rpc.base.ServiceScanner;
import org.rcy.framework.rpc.annotations.RpcInject;
import org.rcy.framework.rpc.config.ServerConfig;
import org.rcy.framework.rpc.service.ServerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

public class RpcServiceScanner implements ServiceScanner, ApplicationContextAware {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private ApplicationContext applicationContext;
	private Class<? extends Annotation> annotationClass = RpcInject.class;
	
	private ServerConfig config;

	public RpcServiceScanner(ServerConfig config) {
		super();
		this.config = config;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public List<RpcService> scanServices() {
		List<RpcService> list = new ArrayList();
		String[] serviceNames = applicationContext.getBeanNamesForAnnotation(annotationClass);
		String globalGroup = config.getGroup();
		for (String name : serviceNames) {
			Object bean = applicationContext.getBean(name);
			logger.debug("find annotated bean:{}",bean);
			try {
				RpcInject annotation = (RpcInject) applicationContext.findAnnotationOnBean(name, annotationClass);
				String group = RpcUtils.determineGroup(globalGroup, annotation.group());
				//获取bean注解上的version信息
				String version = annotation.version();
				AbstractRpcService service = new ServerService(group,version,bean);
				// 检查注解中的serviceClass
				Class<?> serviceInterface = annotation.serviceInterface();
				if (serviceInterface.isInterface() && serviceInterface != Serializable.class) {
					logger.debug("Find annotated serviceInterface [{}] for {}", serviceInterface, bean);
					service.setServiceClass(serviceInterface);
				}
				list.add(service);
			} catch (Exception e) {
				logger.error("error while scanService :{}",bean,e);
			}
		}
		return list;
	}
}